package com.qf.agro.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.qf.agro.common.sys.CustomerException;
import com.qf.agro.common.sys.SysUserHolder;
import com.qf.agro.mapper.sys.SysModuleMapper;
import com.qf.agro.mapper.sys.SysRoleMapper;
import com.qf.agro.pojo.sys.SysRole;
import com.qf.agro.service.sys.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysModuleMapper sysModuleMapper;
    @Override
    public Page<SysRole> findPage(Integer pageNum, Integer pageSize, String name) {
        Page<SysRole> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),SysRole::getName,name);
        page = sysRoleMapper.selectPage(page, queryWrapper);

        return page;
    }

    @Override
    public void addSysRole(SysRole sysRole) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(sysRole.getName()),SysRole::getName,sysRole.getName());
        SysRole sysRole1 = sysRoleMapper.selectOne(queryWrapper);
        if (sysRole1!=null){
            throw new CustomerException("角色已存在，请确认");
        }


        sysRoleMapper.insert(sysRole);
    }
/*
    @Override
    public void deleteSysRole(Long id) {

        sysRoleMapper.deleteById(id);
    }*/

    @Override
    public void editSysRole(SysRole sysRole) {
        sysRoleMapper.updateById(sysRole);
    }

    @Override
    public List<Long> findUserRole(Long userId) {
        return sysRoleMapper.selectUserRole(userId);
    }

    @Override
    public List<SysRole> findAll() {
        LambdaQueryWrapper<SysRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getCompanyId, SysUserHolder.get().getCompanyId());
        return sysRoleMapper.selectList(queryWrapper);
    }


    @Override
    public void updateUserRole(Long userId, List<Long> roleIds) {
        sysRoleMapper.deleteUserRole(userId);
        sysRoleMapper.insertUserRole(userId, roleIds);
    }

    @Override
    public void delete(Long id) {
        //1.根据角色id查询是否有模块关联
        List<Long> moduleList =  sysModuleMapper.selectByRoleId(id);
        //3.判断
        if(moduleList == null || moduleList.size() == 0) {
            sysRoleMapper.deleteById(id);
        }else {
            throw new CustomerException("该角色有权限关联，请先删除权限");
        }
    }

}
